<template>
  <div>
    <el-button @click="showDialog()" type="primary" icon="el-icon-plus" style="margin: 10px 0px;">添加</el-button>

    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" label="序号" width="80px" align="center">
      </el-table-column>

      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <!-- 作用域插槽 -->
      <!-- 这里的<el-table-column>在整个<el-table>的上下文中可以被视为一个子组件。它通过作用域插槽将数据（这里是当前行的数据row和行索引$index）
        传递给父组件（可能是包含<el-table>的组件）。
          父组件通过<template slot-scope="{row,$index}">...</template>来接收这些数据并进行自定义的渲染。 -->

      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template slot-scope="{row,$index}">
          <!-- {{ row }}{{ $index }}  element-ui 写法-->
          <img :src="row.logoUrl" style="width: 100px;height: 100px;">
        </template>
      </el-table-column>

      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)"> 删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- pager-count是设置 显示页数的按钮 的个数  -->
    <el-pagination style="margin-top: 20px; text-align: center;" :current-page="page" :page-sizes="[3, 5, 10]"
      :page-size="limit" layout="prev,pager,next,jumper,->,sizes,total" :total="total" :pager-count="7"
      @current-change="getPageList" @size-change="handleSizeChange">
    </el-pagination>

    <!-- 对话框 -->
    <!-- :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" -->
    <el-dialog :title="tmForm.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">

      <el-form style="width: 80%;" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="添加LOGO" label-width="100px" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>


export default {
  name: "tradeMark",
  data() {
    var calidateTmName = (rule, value, callback) => {
      if (value.trim().length < 2 || value.trim().length > 10) {
        callback(new Error('请输入2-10位字符'));
      } else {
        callback();//放行
      }
    };
    return {
      page: 1,
      limit: 3,
      list: [],
      total: undefined,
      dialogFormVisible: false,
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },//trigger:什么行为触发
          { validator: calidateTmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌的图片', trigger: 'change' }
        ],
      }
    }
  },
  mounted() {
    // console.log(this.$API);
    this.getPageList();
  },
  methods: {
    async getPageList(pager = 1) {//pager是饿了吗UI组件，封装的函数数据
      this.page = pager
      const { page, limit } = this;
      let result = await this.$API.tradeMark.reqTradeMarkList(page, limit)
      // console.log(result);
      if (result.code == 200) {
        this.total = result.data.total
        this.list = result.data.records
      }
    },
    handleSizeChange(limit) {
      this.limit = limit
      this.getPageList()
    },

    showDialog() {
      this.dialogFormVisible = true;
      this.tmForm = {
        tmName: "",
        logoUrl: ""
      }
    },
    updateTradeMark(row) {
      this.dialogFormVisible = true;
      // console.log(row);

      // this.tmForm = row; //将已有的品牌信息，展示出来,这样直接赋值，点击取消按钮，也会修改内容，下面用浅拷贝实现就不会
      this.tmForm = { ...row }
      // console.log(this.tmForm);

    },

    handleAvatarSuccess(res, file) {
      // console.log(res, file);

    },
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    addOrUpdateTradeMark() {

      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          this.dialogFormVisible = false;
          let result = await this.$API.tradeMark.reqAddOrUpdateTradeMark(this.tmForm)
          if (result.code == 200) {
            this.$message({
              type: 'success',
              message: this.tmForm.id ? "修改品牌成功" : "添加品牌成功"
            })
            //修改时，如果需要停留在那一页
            this.getPageList(this.tmForm.id ? this.page : 1)

          }
        } else {
          alert('提交错误')
          return false;
        }
      })
    },
    deleteTradeMark(row) {

      this.$confirm(`你确定删除${row.tmName}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // console.log(this.$API.tradeMark);

        let result = await this.$API.tradeMark.reqDeleteTradeMark(row.id);
        // console.log(result);
        if (result.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
        this.getPageList(this.list.length > 1 ? this.page : this.page - 1)//注意list仅包含当前页面的数据条数，并不是所有的数据条数
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }

}



</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>